#!/bin/sh

#
# Copyright (c) 2006, 2007 Hong Mingjian
# All rights reserved.
#
# This piece of code is distributed with GPLv2 license.
#

TEXMF=/cygdrive/d/texmf-local  	# CHANGE_THIS
TTF2TFM=ttf2tfm			# CHANGE_THIS

if [ $# -ge 1 ]; then
	if [ ! -r $1 ]; then
	    echo "No such file: $1"
	    exit 1
	fi
	infile=$1
fi

SFD=$(kpsewhich Unicode.sfd)
if [ -z "${SFD}" ] ; then
    echo "'Unicode.sfd' not found"
    exit 1
fi

if [ ! -d ${TEXMF}/web2c ]; then
    mkdir -p ${TEXMF}/web2c
fi

UPDMAPCFG=${TEXMF}/web2c/updmap.cfg
if [ ! -f ${UPDMAPCFG} ]
then
    cp -v $(kpsewhich -format 'web2c files' updmap.cfg) ${UPDMAPCFG}
fi

templ=`basename $0`
WORK=`mktemp -d /tmp/${templ}.XX`
cd ${WORK}

while read font file
do
    if [ -z "${font}" -o -z "${file}" ]; then
	continue
    fi

    if [ ! -f ${file} ]; then
	continue
    fi

    # ${font} - Font name
    # ${file} - Font file name

    if [ ! -d ${TEXMF}/fonts/truetype ]; then
	mkdir -p ${TEXMF}/fonts/truetype
    fi

    if [ ! -f ${TEXMF}/fonts/truetype/$(basename ${file}) ]; then
	cp -v ${file} ${TEXMF}/fonts/truetype
    fi

    ${TTF2TFM} d:/texmf-local/fonts/truetype/$(basename ${file}) -q -w ${font}@${SFD}@
    #${TTF2TFM} ${TEXMF}/fonts/truetype/$(basename ${file}) -q -w ${font}@${SFD}@

    for i in `ls *.tfm | cut -d. -f1`; do
	echo "${i} <$(basename ${file}) <${i}.enc";
    done > ${font}.map
    if [ ! -d ${TEXMF}/fonts/map/pdftex/CJK ]; then
	mkdir -p ${TEXMF}/fonts/map/pdftex/CJK
    fi

    mv ${font}.map ${TEXMF}/fonts/map/pdftex/CJK
    echo "Map ${font}.map" >> ${UPDMAPCFG}

    if [ ! -d ${TEXMF}/fonts/tfm/CJK/${font} ]; then
	mkdir -p ${TEXMF}/fonts/tfm/CJK/${font}
    fi
    mv ${font}*.tfm ${TEXMF}/fonts/tfm/CJK/${font}

    if [ ! -d ${TEXMF}/fonts/enc/pdftex/CJK/${font} ]; then
	mkdir -p ${TEXMF}/fonts/enc/pdftex/CJK/${font}
    fi
    mv ${font}*.enc ${TEXMF}/fonts/enc/pdftex/CJK/${font}

    if [ ! -d ${TEXMF}/tex/latex/CJK/UTF8 ]; then
	mkdir -p ${TEXMF}/tex/latex/CJK/UTF8
    fi
    cat >${TEXMF}/tex/latex/CJK/UTF8/c70${font}.fd <<EOF
% character set: Unicode U+0080 - U+FFFD
% font encoding: Unicode
\ProvidesFile{c70${font}.fd}
\DeclareFontFamily{C70}{${font}}{\hyphenchar \font\m@ne}
\DeclareFontShape{C70}{${font}}{m}{n}{<-> CJK * ${font}} {}
\DeclareFontShape{C70}{${font}}{bx}{n}{<-> CJKb * ${font}}{\CJKbold}
\endinput
EOF

done < $(realpath ${infile})

rmdir ${WORK}

updmap
#updmap-sys

mktexlsr

# end of file

